package com.example.zp.liaotian;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.demo.PayDemoActivity;
import com.example.jbmsuppliers.R;
import com.example.weather.myframe.PopupSelectImage;
import com.example.zp.IndexBar.widget.RecordButton;
import com.example.zp.adapters.MainGridAdapter;
import com.example.zp.sqldata.MySqliteUtlis;
import com.example.zp.utils.AudioRecorder;
import com.jbm.core.common.AccountCtrl;
import com.jbm.core.common.MainServer;
import com.jbm.core.iface.IAcross;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends Activity implements OnClickListener,View.OnLayoutChangeListener {
	/** Called when the activity is first created. */

	private Button mBtnSend;
	private RecordButton mBtnRcd;
	private Button mBtnBack;
	private EditText mEditTextContent;
	private RelativeLayout mBottom;
	private ListView mListView;
	private ChatMsgViewAdapter mAdapter;
	private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();
	private boolean isShosrt = false;
	private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
			voice_rcd_hint_tooshort;
	private ImageView img1, sc_img1;
	private SoundMeter mSensor;
	private LinearLayout del_re;
	private ImageView chatting_mode_btn, volume;
	private boolean btn_vocie = false;
	private int flag = 1;
	private Handler mHandler = new Handler();
	private String voiceName;
	private long startVoiceT, endVoiceT;
	private Button btn_more;
	private LinearLayout ll_more;
	private boolean MORE_DISPLAY_HIDE = true;
	private String mEditText;
	private TextView btn_businesscard,btn_collection;
	private int to_id,local_id;
	private MyBroadCat broa;
	IntentFilter file = null;
	private MySqliteUtlis sql;
	private TextView tv_to_name;
	//Activity最外层的Layout视图
	private LinearLayout activityRootView;
	private GridView hidder_gv;
	//屏幕高度
	private int screenHeight = 0;
	private int keyHeight = 0;


	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);
		// 启动activity时不自动弹出软键盘
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		Intent intent = getIntent();
		to_id = intent.getExtras().getInt("t_ID");
		local_id = intent.getExtras().getInt("local_id");
//		ICallGroup icg = (ICallGroup) MainServer.g_server.CreateGroup();
		file = new IntentFilter();
		file.addAction("MSG");
		file.addAction("CG");
		broa = new MyBroadCat();
		registerReceiver(broa, file);
		//获取屏幕高度
		screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
		//阀值设置为屏幕高度的1/3
		keyHeight = screenHeight/3;

		initView();

		initData();

//		if(String.valueOf(to_id).equals("1")){
//			ICallGroup icg = (ICallGroup) MainServer.g_server.CreateGroup();
//			if ( icg.m_code == 200 ){
//				int cg_id = icg.m_cg_id;
//			}
//
//		}
	}
	//文本框实时监听
	private TextWatcher watcher = new TextWatcher() {
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {

		}
		//输入文字后的状态
		@Override
		public void afterTextChanged(Editable s) {
			mEditText = mEditTextContent.getText().toString();
			if (mEditText.equals("")){
				mBtnSend.setVisibility(View.GONE);
				btn_more.setVisibility(View.VISIBLE);
			}else {
				mBtnSend.setVisibility(View.VISIBLE);
				btn_more.setVisibility(View.INVISIBLE);
			}
		}
	};
	private void visible() {
		final LinearLayout.LayoutParams params = ( LinearLayout.LayoutParams)ll_more.getLayoutParams();
		ObjectAnimator anim = ObjectAnimator//
				.ofInt(ll_more, "zhy",0,  780)//
				.setDuration(800);//
		anim.start();
		anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
		{
			@Override
			public void onAnimationUpdate(ValueAnimator animation)
			{
				int cVal = (int) animation.getAnimatedValue();
				params.height=cVal;
				ll_more.requestLayout();

			}
		});
	}
	private void hidden() {
		final LinearLayout.LayoutParams params = ( LinearLayout.LayoutParams)ll_more.getLayoutParams();
		ObjectAnimator anim = ObjectAnimator//
				.ofInt(ll_more, "zhy",780,  0)//
				.setDuration(800);//
		anim.start();
		anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
		{
			@Override
			public void onAnimationUpdate(ValueAnimator animation)
			{
				int cVal = (int) animation.getAnimatedValue();
				Log.e("main","数据"+cVal);
				params.height=cVal;
				ll_more.requestLayout();

			}
		});
	}
	public void initView() {
		mListView = (ListView) findViewById(R.id.listview);
		mBtnSend = (Button) findViewById(R.id.btn_send);
		mBtnRcd = (RecordButton) findViewById(R.id.btn_rcd);
		mBtnSend.setOnClickListener(this);
		mBtnBack = (Button) findViewById(R.id.btn_back);
		mBottom = (RelativeLayout) findViewById(R.id.btn_bottom);
		mBtnBack.setOnClickListener(this);
		chatting_mode_btn = (ImageView) this.findViewById(R.id.ivPopUp);
		volume = (ImageView) this.findViewById(R.id.volume);
		img1 = (ImageView) this.findViewById(R.id.img1);
		sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
		del_re = (LinearLayout) this.findViewById(R.id.del_re);
		btn_more = (Button) findViewById(R.id.btn_more);
		//这个是功能列表
		hidder_gv=(GridView)findViewById(R.id.hidder_gv);
		hidder_gv.setAdapter(new MainGridAdapter(this));
		//点击下面功能的操作
		hidder_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					switch (position){
						case 0:
							//请求图片
							startActivityForResult(new Intent(MainActivity.this,PopupSelectImage.class),100);
							break;
						case 1:
							Toast.makeText(MainActivity.this,"开门授权",Toast.LENGTH_SHORT).show();
							break;
						case 2:
							startActivity(new Intent(MainActivity.this, PayDemoActivity.class));
							Toast.makeText(MainActivity.this,"支付",Toast.LENGTH_SHORT).show();
							break;
						case 3:
							Toast.makeText(MainActivity.this,"商品列表",Toast.LENGTH_SHORT).show();
							break;
					}
			}
		});


		tv_to_name = (TextView) findViewById(R.id.tv_to_name);
		activityRootView = (LinearLayout) findViewById(R.id.ll_bottom);

		voice_rcd_hint_rcding = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_rcding);
		voice_rcd_hint_loading = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_loading);
		voice_rcd_hint_tooshort = (LinearLayout) this
				.findViewById(R.id.voice_rcd_hint_tooshort);
		ll_more = (LinearLayout) findViewById(R.id.LL_More);
		mSensor = new SoundMeter();
		mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
		chatting_mode_btn
				.setImageResource(R.mipmap.voice);
		//输入框点击监听
		mEditTextContent.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!MORE_DISPLAY_HIDE){
					MORE_DISPLAY_HIDE = true;
					hidden();
					ll_more.setVisibility(View.GONE);
				}
			}
		});
		//输入框变动监听
		mEditTextContent.addTextChangedListener(watcher);

		//更多按钮
		btn_more.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
//				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//				boolean isOpen=imm.isActive(mEditTextContent);//isOpen若返回true，则表示输入法打开
//				if (isOpen){
//					ll_more.setVisibility(View.GONE);
//				}else {
//					if (MORE_DISPLAY_HIDE){
//						MORE_DISPLAY_HIDE = false;
//						ll_more.setVisibility(View.VISIBLE);
//					}else {
//						ll_more.setVisibility(View.GONE);
//						MORE_DISPLAY_HIDE = true;
//					}
//
//				}


				if (MORE_DISPLAY_HIDE){
					MORE_DISPLAY_HIDE = false;
					InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//					((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(MainActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
					imm.hideSoftInputFromWindow(mEditTextContent.getWindowToken(), 0); //强制隐藏键盘
					ll_more.setVisibility(View.VISIBLE);
					visible();
//					ll_more.setVisibility(View.VISIBLE);
				}else{
//					ll_more.setVisibility(View.GONE);
					hidden();
					MORE_DISPLAY_HIDE = true;
				}
			}
		});
		//语音文字切换按钮
		chatting_mode_btn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				if (btn_vocie) {
					mBtnRcd.setVisibility(View.GONE);
					mEditTextContent.setVisibility(View.VISIBLE);
					btn_vocie = false;
					chatting_mode_btn
							.setImageResource(R.mipmap.voice);

				} else {
					mBtnRcd.setVisibility(View.VISIBLE);
					mEditTextContent.setVisibility(View.GONE);
					chatting_mode_btn
							.setImageResource(R.mipmap.keybord);
					btn_vocie = true;
				}
			}
		});
		mBtnRcd.setAudioRecord(new AudioRecorder());

	}

	private String[] msgArray = new String[] { "有人就有恩怨","有恩怨就有江湖","人就是江湖","你怎么退出？ ","生命中充满了巧合","两条平行线也会有相交的一天。"};

	private String[] dataArray = new String[] { "2012-10-31 18:00",
			"2012-10-31 18:10", "2012-10-31 18:11", "2012-10-31 18:20",
			"2012-10-31 18:30", "2012-10-31 18:35"};
	private final static int COUNT = 6;


	public void initData() {
//		for (int i = 0; i < COUNT; i++) {
//			ChatMsgEntity entity = new ChatMsgEntity();
//			entity.setDate(dataArray[i]);
//			if (i % 2 == 0) {
//				entity.setName(to_id+"");
//				entity.setMsgType(true);
//			} else {
//				entity.setName(local_id+"");
//				entity.setMsgType(false);
//			}
		tv_to_name.setText(String.valueOf(to_id));
			mDataArrays = MySqliteUtlis.GetInstan(this).showChatData(to_id,local_id);
			Log.e("xiaoxi:",mDataArrays.toString());
//			entity.setText(msgArray[i]);
//			mDataArrays.add(entity);
//		Log.e("shoudao:",MySqliteUtlis.GetInstan(this).showChatData(local_id,to_id).get(1).getName());
//		}
		if (mDataArrays.size() <-1){
			return;
		}else {
			mAdapter = new ChatMsgViewAdapter(this, mDataArrays, to_id, local_id, new ChatMsgViewAdapter.JumpInterface() {
				@Override
				public void scroll() {
					mListView.setSelection(mListView.getBottom());
				}
			});
		mListView.setAdapter(mAdapter);
		}

	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_send:
			send();
			break;
		case R.id.btn_back:
			finish();
			break;
		}
	}

	private void send() {
		final String contString = mEditTextContent.getText().toString();
		if (contString.length() > 0) {
			ChatMsgEntity entity = new ChatMsgEntity();
			entity.setDate(getDate());
			entity.setName(local_id+"");
			entity.setTo_id(to_id);
			entity.setLocal_id(local_id);
//			entity.setMsgType(false);
			entity.setText(contString);
			new Thread(new Runnable() {
				@Override
				public void run() {
					AccountCtrl.g_accountctrl.GetCA(to_id,"app_mobile");
					IAcross ars = MainServer.g_server.SendText(to_id,"app_mobile",contString);
					Log.e("fasong:",ars.m_info + " " + ars.m_code);
				}
			}).start();
//			MySqliteUtlis.GetInstan(this).StoringChatData(to_id,contString,local_id,getDate(), String.valueOf(local_id),"1");
//			mDataArrays.add(entity);
			mDataArrays = MySqliteUtlis.GetInstan(this).showChatData(to_id,local_id);
//			mAdapter = new ChatMsgViewAdapter(this, mDataArrays,to_id,local_id);
//			mListView.setAdapter(mAdapter);
//			mAdapter.notifyDataSetChanged();
			mEditTextContent.setText("");
			mListView.setSelection(mListView.getCount() - 1);
		}
	}

	private String getDate() {
		Calendar c = Calendar.getInstance();

		String year = String.valueOf(c.get(Calendar.YEAR));
		String month = String.valueOf(c.get(Calendar.MONTH));
		String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
		String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
		String mins = String.valueOf(c.get(Calendar.MINUTE));

		StringBuffer sbBuffer = new StringBuffer();
		sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
				+ mins);

		return sbBuffer.toString();
	}


	private static final int POLL_INTERVAL = 300;



	public void head_xiaohei(View v) { // 标题栏 返回按钮

	}

	@Override
	public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
		if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){
//			Toast.makeText(MainActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();
		}else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){
//			Toast.makeText(MainActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();
		}
	}

	class MyBroadCat extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			mListView.setSelection(mListView.getBottom());
			initData();
			mAdapter.notifyDataSetChanged();

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=RESULT_OK){
			return;
		}
		switch(requestCode) {
			//选择图片回调
			case 100:
				File file = (File) data.getSerializableExtra("file");
				//回调 返回文件
				Toast.makeText(this, "文件名"+file.getAbsolutePath(), Toast.LENGTH_SHORT).show();

				break;
		}};
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(broa);
	}

	@Override
	protected void onResume() {
		super.onResume();
		//添加layout大小发生改变监听器
		activityRootView.addOnLayoutChangeListener(this);
	}
}